﻿#include "Caelum.h"

namespace Caelum {

	Console::Console()
	{

	}

	void Console::Initialize(ConsoleParams &cParams)
	{
		AllocConsole();
		AttachConsole(GetProcessId(GetModuleHandle(NULL)));

		this->handles.hOut = (unsigned long)GetStdHandle(STD_OUTPUT_HANDLE);
		this->handles.hIn = (unsigned long)CreateFile(L"CONIN$", GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_FLAG_OVERLAPPED, NULL);
		this->handles.hErr = (unsigned long)GetStdHandle(STD_ERROR_HANDLE);

		FILE *consoleOut = _fdopen(_open_osfhandle((long)this->handles.hOut, _O_TEXT), "wt");
		FILE *consoleIn = _fdopen(_open_osfhandle((long)this->handles.hIn, _O_TEXT), "rt");
		FILE *consoleErr = _fdopen(_open_osfhandle((long)this->handles.hErr, _O_TEXT), "wt");

		SetConsoleTitle(cParams.Title.c_str());

			CONSOLE_FONT_INFOEX fontInfo;
		fontInfo.cbSize = sizeof(CONSOLE_FONT_INFOEX);
		fontInfo.nFont = 1;
		fontInfo.dwFontSize.Y = cParams.FontSize;
		fontInfo.FontWeight = 400;
		fontInfo.FontFamily = 54;
		lstrcpyW(fontInfo.FaceName, L"Consolas");
		if(SetCurrentConsoleFontEx((HANDLE)this->handles.hOut, FALSE, &fontInfo) == 0)
		{
			std::wcout << GetLastError();
		}

		if(cParams.OverrideSTDIO)
		{
			*stdout = *consoleOut;
			*stdin = *consoleIn;
			*stderr = *consoleErr;
			setvbuf(consoleOut, NULL, _IONBF, 0);
			setvbuf(consoleIn, NULL, _IONBF, 0);
			setvbuf(consoleErr, NULL, _IONBF, 0);
			std::ios::sync_with_stdio();
		}
	}

	void Console::ProcessInput(std::wstring input)
	{

	}

	Console::~Console()
	{
		CloseHandle((HANDLE)this->handles.hIn);
	}
	
}